package com.wanghua.spring.action;

import com.opensymphony.xwork2.ActionSupport;
import org.apache.struts2.ServletActionContext;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import javax.servlet.ServletContext;
import java.io.*;

/*Struts2也支持同时上传多个文件，只要将下面的 File 改成 File[] 或 List<File> 类型的变量，并使用多个同名的<struts:file /> 标签即可。
  Struts2仍然使用 apache commons-fileupload 组件实现文件上传。*/
@Scope("prototype")
@Controller("uploadAction")
public class UploadAction extends ActionSupport {
    private File picture; //上传的文件。Struts2会将上传的文件封装为 File 对象。
    private String pictureContentType;  //文件类型。Struts2会将上传文件的文件类型设置到此属性上。因此属性必须约定为"xxxContentType"，"xxx"为 File 属性的名称。
    private String pictureFileName;  //文件名称。Struts2会将上传文件的文件类型设置到此属性上。因此属性必须约定为"xxxFileName"，"xxx"为 File 属性的名称。

    @Override
    public String execute() throws Exception {
        ServletContext servletContext = ServletActionContext.getServletContext();

        String saveFilePath = servletContext.getRealPath("/upload");
        File saved = new File(saveFilePath, pictureFileName);

        InputStream ins = null;
        OutputStream ous = null;
        try {
            saved.getParentFile().mkdirs();
            ins = new FileInputStream(picture);
            ous = new FileOutputStream(saved);

            byte[] b = new byte[1024];
            int len = 0;
            while ((len = ins.read(b)) != -1) {
                ous.write(b, 0, len);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (ous != null) ous.close();
            if (ins != null) ins.close();
        }
        return "list";
    }

    public File getPicture() {
        return picture;
    }

    public void setPicture(File picture) {
        this.picture = picture;
    }

    public String getPictureContentType() {
        return pictureContentType;
    }

    public void setPictureContentType(String pictureContentType) {
        this.pictureContentType = pictureContentType;
    }

    public String getPictureFileName() {
        return pictureFileName;
    }

    public void setPictureFileName(String pictureFileName) {
        this.pictureFileName = pictureFileName;
    }
}
